{% extends 'layout.html' %}
{% block css %}
    <link rel="stylesheet" href="/static/ztree/css/bootstrapStyle/bootstrapStyle.css" type="text/css">
    <style>
        .redstar::after {
            content: '*';
            color: red;
        }

        #td_textarea {
            display: block;
            width: 100%;
            height: 40px;
            border: none;
        }

        table, table th, tbody, tbody td {
            border: 3px solid #eaeaea;
        }
    </style>
{% endblock %}
{% block content %}

    <section id="main-content">
        <div class="row">

            <div class="col-lg-12">


                <div class="card card-default">
                    <div class="card-header card-header-border-bottom">
                        <h2>定义一个新的接口
                            <button type="button" class="btn btn-primary btn-default api_define_add"
                                    style="right: 50px;position: fixed">保存
                            </button>
                        </h2>
                    </div>

                    <div class="card-body">
                        <div class="row">
                            {#基本信息#}
                            <div class="input-group input-group-default">
                                <div class="col-sm-2">
                                    <div class="form-group">
                                        <label for="fname" class="redstar">接口名称</label>
                                        <input type="text" class="form-control" placeholder="请输入接口名称" id="api_name"
                                               value="{{ api_define.name }}">
                                    </div>
                                </div>
                                <div class="col-sm-2">
                                    <div class="form-group">
                                        <label for="fname" class="redstar">所属模块</label>
                                        <select class="form-control" id="api_module">
                                            {% for modules in modules_list %}
                                                <option value="{{ modules.id }}">{{ modules.name }}</option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>
                                <div class="col-sm-2">
                                    <div class="form-group">
                                        <label for="fname" class="redstar">负责人</label>
                                        <select class="form-control" id="api_user">
                                            {% for user in users %}
                                                <option value="{{ user.id }}">{{ user }}</option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>
                                <div class="col-sm-2">
                                    <div class="form-group">
                                        <label for="fname" class="redstar">状态</label>
                                        <select id="api_status" class="form-control">
                                            <option value="0">待执行</option>
                                            <option value="1">进行中</option>
                                            <option value="2">执行失败</option>
                                            <option value="3">已关闭</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-sm-4">
                                    <div class="form-group">
                                        <label for="fname">接口描述</label>
                                        <textarea type="text" class="form-control" placeholder=""
                                                  id="api_describe"></textarea>
                                    </div>
                                </div>
                            </div>

                            {#接口请求#}
                            <div class="input-group input-group-default">
                                <div class="col-sm-10">
                                    <div class="input-group input-group-default">
                                        <select class="btn btn-primary" id="api_method">
                                            <option value="0">GET</option>
                                            <option value="1">POST</option>
                                            <option value="2">PUT</option>
                                            <option value="3">DELETE</option>
                                        </select>
                                        <input type="text" placeholder="Enter Request Url" name="Search"
                                               id="api_url" class="form-control">
                                        <button class="btn btn-primary" onclick="request_test()">send

                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-12">
                                <div class="card">
                                    <div class="card-body p-b-0 ">
                                        <!-- params - headers-- -->
                                        <ul class="nav nav-tabs customtab2" role="tablist">
                                            <li class="nav-item">
                                                <a class="nav-link active show" data-toggle="tab"
                                                   href="#params" role="tab" aria-selected="true">
                                                    <span class="hidden-xs-down">params</span></a>
                                            </li>
                                            <li class="nav-item">
                                                <a class="nav-link" data-toggle="tab"
                                                   href="#headers" role="tab" aria-selected="false">
                                                    <span class="hidden-xs-down">headers</span></a></li>
                                            <li class="nav-item">
                                                <a class="nav-link" data-toggle="tab" href="#body" role="tab"
                                                   aria-selected="false">
                                                    <span class="hidden-xs-down">body</span></a></li>
                                            <li class="nav-item">
                                                <a class="nav-link" data-toggle="tab" href="#assert" role="tab"
                                                   aria-selected="false">
                                                    <span class="hidden-xs-down">assert</span></a></li>
                                        </ul>
                                        <!-- Tab panes -->
                                        <div class="tab-content">
                                            <div class="tab-pane  p-20 active show form-group" id="params"
                                                 role="tabpanel">
                                                {#                                                params#}
                                                <div class="card-body">
                                                    <div class="table-responsive" style="text-align: left;">
                                                        <table class="table"
                                                               style="border-collapse: collapse;width: 100%">
                                                            <thead>
                                                            <tr>
                                                                <th>KEY</th>
                                                                <th style="text-align: left;">VALUE</th>
                                                                <th style="text-align: center;width: 20px">
                                                                    <button class="btn btn-primary glyphicon glyphicon-plus"
                                                                            onclick="params_add()">
                                                                        <i class="ti-plus"></i></button>
                                                                </th>
                                                            </tr>
                                                            </thead>
                                                            <tbody id="params_body">
                                                            <tr id="params_tr">
                                                                <td id="api_define_module"><textarea type="text"
                                                                                                     name="params_key"
                                                                                                     placeholder="KEY"
                                                                                                     id='td_textarea'></textarea>
                                                                </td>
                                                                <td id="api_define_name"><textarea type="text"
                                                                                                   name="params_value"
                                                                                                   placeholder="VALUE"
                                                                                                   id='td_textarea'></textarea>
                                                                </td>
                                                                <td>

                                                                </td>
                                                            </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>

                                                </div>


                                            </div>
                                            <div class="tab-pane  p-20 form-group" id="headers" role="tabpanel">
                                                {#                                                headers#}
                                                <div class="card-body">
                                                    <div class="table-responsive" style="text-align: left;">
                                                        <table class="table"
                                                               style="border-collapse: collapse;width: 100%">
                                                            <thead>
                                                            <tr>
                                                                <th>KEY</th>
                                                                <th style="text-align: left;">VALUE</th>
                                                                <th style="text-align: center;width: 20px">
                                                                    <button class="btn btn-primary glyphicon glyphicon-plus"
                                                                            onclick="headers_add()">
                                                                        <i class="ti-plus"></i></button>
                                                                </th>
                                                            </tr>
                                                            </thead>
                                                            <tbody id="headers_body">
                                                            <tr id="params_tr">
                                                                <td id="api_define_module"><textarea type="text"
                                                                                                     name="headers_key"
                                                                                                     placeholder="KEY"
                                                                                                     id='td_textarea'></textarea>
                                                                </td>
                                                                <td id="api_define_name"><textarea type="text"
                                                                                                   name="headers_value"
                                                                                                   placeholder="VALUE"
                                                                                                   id='td_textarea'></textarea>
                                                                </td>
                                                                <td>

                                                                </td>
                                                            </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>

                                                </div>
                                            </div>
                                            <div class="tab-pane p-20 form-group" id="body" role="tabpanel">
                                                <ul class="list-unstyled list-inline" id="body_choice"
                                                    onchange="body_choice_change(this)">
                                                    <li class="d-inline-block mr-3">
                                                        <input type="radio" name="body_option" checked value="5">
                                                        <label class="control">none
                                                        </label></li>
                                                    <li class="d-inline-block mr-3">
                                                        <input type="radio" name="body_option" value="0">
                                                        <label class="control">form-data
                                                        </label></li>
                                                    <li class="d-inline-block mr-3">
                                                        <input type="radio" name="body_option"
                                                               value="1">
                                                        <label class="control">x-www-form-urlencoded
                                                        </label></li>
                                                    <li class="d-inline-block mr-3">
                                                        <input type="radio" name="body_option" value="2">
                                                        <label class="control">json
                                                        </label></li>
                                                    <li class="d-inline-block mr-3">
                                                        <input type="radio" name="body_option" value="3">
                                                        <label class="control">xml
                                                        </label></li>

                                                </ul>
                                                <textarea name="params_text" class="form-control" id="api_body"
                                                          placeholder='{"name":"user"}'></textarea>
                                                <div class="tab-pane  p-20 form-group" id="body_form" role="tabpanel">
                                                    {#                                                headers#}
                                                    <div class="card-body">
                                                        <div class="table-responsive" style="text-align: left;">
                                                            <table class="table"
                                                                   style="border-collapse: collapse;width: 100%">
                                                                <thead>
                                                                <tr>
                                                                    <th>KEY</th>
                                                                    <th style="text-align: left;">VALUE</th>
                                                                    <th style="text-align: center;width: 20px">
                                                                        <button class="btn btn-primary glyphicon glyphicon-plus"
                                                                                onclick="body_add()">
                                                                            <i class="ti-plus"></i></button>
                                                                    </th>
                                                                </tr>
                                                                </thead>
                                                                <tbody id="body_body">
                                                                <tr id="body_tr">
                                                                    <td id="api_define_module"><textarea type="text"
                                                                                                         name="body_key"
                                                                                                         placeholder="KEY"
                                                                                                         id='td_textarea'></textarea>
                                                                    </td>
                                                                    <td id="api_define_name"><textarea type="text"
                                                                                                       name="body_value"
                                                                                                       placeholder="VALUE"
                                                                                                       id='td_textarea'></textarea>
                                                                    </td>
                                                                    <td>

                                                                    </td>
                                                                </tr>
                                                                </tbody>
                                                            </table>
                                                        </div>

                                                    </div>
                                                </div>
                                            </div>
                                            <div class="tab-pane p-20 form-group" id="assert" role="tabpanel">
                                                <span style="font-size: 15px">是否需要断言：</span>
                                                <input type="checkbox" class="checkbox"/>
                                                <ul class="list-unstyled list-inline" id="assert_choice">
                                                    <li class="d-inline-block mr-3">
                                                        <input type="radio" name="assert_option" value="0" checked>
                                                        <label class="control">匹配
                                                        </label>
                                                    </li>
                                                    <li class="d-inline-block mr-3">
                                                        <input type="radio" name="assert_option" value="1">
                                                        <label class="control">包含
                                                        </label>
                                                    </li>
                                                    <li class="d-inline-block mr-3">
                                                        <input type="radio" name="assert_option" value="2">
                                                        <label class="control">状态码
                                                        </label>
                                                    </li>

                                                </ul>
                                                <textarea type="text" class="form-control"
                                                          id="api_assert">{{ api_define.assert_body }}</textarea>

                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-12">
                                <div class="card">
                                    <div class="card-body p-b-0 ">
                                        <h6>Respone</h6>
                                    </div>
                                </div>
                            </div>

                        </div>


                    </div>
                </div>
            </div>
        </div>


    </section>

{% endblock %}
{% block js %}

    {#    单选框改变操作#}
    <script>
        function body_choice_change(obj) {
            console.log($("input[name='body_option']:checked").val())
            if ($("input[name='body_option']:checked").val() == 0 || $("input[name='body_option']:checked").val() == 1) {
                $('#body_form').show()
                $('#api_body').hide()
            }
            if ($("input[name='body_option']:checked").val() == 2 || $("input[name='body_option']:checked").val() == 3) {
                $('#body_form').hide()
                $('#api_body').show()
            }
            if ($("input[name='body_option']:checked").val() == 5) {
                $('#body_form').hide()
                $('#api_body').hide()
            }

        }
    </script>

    <script type="text/javascript">

        $(function () {
            $(".checkbox").bootstrapSwitch({
                onText: "是",      // 设置ON文本
                offText: "否",    // 设置OFF文本
                onColor: "success",// 设置ON文本颜色
                offColor: "danger",  // 设置OFF文本颜色
                size: "mini",    // 设置控件大小,从小到大
                handleWidth: "35",//设置控件宽度
            });
            $("#body_form").hide()
            $("#api_body").hide()
        });

    </script>

    <script>
        function params_del(obj) {
            //找爷爷
            var reprent = obj.parentNode.parentNode;
            reprent.remove();
        }

        function headers_del(obj) {
            //找爷爷
            var reprent = obj.parentNode.parentNode;
            reprent.remove();
        }

        function body_del(obj) {
            //找爷爷
            var reprent = obj.parentNode.parentNode;
            reprent.remove();
        }
    </script>

    <script>

        function request_test() {
            var api_method = $("#api_method").find("option:selected").text()
            var api_url = $('#api_url').val()
            var api_params = {}
            for (var i = 0; i < $('.table').find('textarea[name="params_key"]').length; i++) {
                if ($('.table').find('textarea[name="params_key"]')[i].value) {
                    api_params[$('.table').find('textarea[name="params_key"]')[i].value] = $('.table').find('textarea[name="params_value"]')[i].value
                }
            }
            var api_headers = {}
            for (var i = 0; i < $('.table').find('textarea[name="headers_key"]').length; i++) {
                if ($('.table').find('textarea[name="headers_key"]')[i].value) {
                    api_headers[$('.table').find('textarea[name="headers_key"]')[i].value] = $('.table').find('textarea[name="headers_value"]')[i].value
                }
            }
            var body_choice = $("input[name='body_option']:checked").val()
            var api_body = $('#api_body').val()
            console.log(api_method, api_url, api_params, api_headers, api_body)
            if (api_url) {
                $.ajax({
                    url: "{% url 'apitests:api_define_request_test' %}",
                    type: "POST",
                    data: {
                        "api_method": api_method,
                        "api_url": api_url,
                        "api_params": JSON.stringify(api_params),
                        "api_headers": JSON.stringify(api_headers),
                        "body_choice": body_choice,
                        "api_body": api_body,
                    },
                    beforeSend: function (xhr, settings) {
                        xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                    },
                    success: function (data) {
                        if (data.status) {
                            swal({
                                title: "返回信息",
                                text: "响应时间：" + data.rep_time + "ms" + '\n' +
                                    "响应状态码：" + data.rep_status_code + ' ' + data.rep_reason + '\n' +
                                    "响应数据：" + JSON.stringify(data.rep_json_data) + '\n',
                                {#timer: 1000,#}
                                {#showConfirmButton: false,#}
                            });
                        } else {
                            swal({
                                title: data.error_msg,
                                timer: 1000,
                                showConfirmButton: false,
                            });
                        }
                    },
                })

            } else {
                swal("数据请填写完整")

            }
        }
    </script>


    <script>
        function params_add() {
            {#判断key是否有值#}
            if ($('.table').find('textarea[name="params_key"]')[$('.table').find('textarea[name="params_key"]').length - 1].value) {
                var son = document.createElement('tr')
                son.innerHTML = '<td id="api_define_module"><textarea type="text" name="params_key"  ' +
                    'placeholder="KEY"id="td_textarea"></textarea> </td><td id="api_define_name">' +
                    '<textarea type="text" name="params_value"placeholder="VALUE"  id="td_textarea"></textarea>' +
                    '</td><td><button onclick="params_del(this)" class="btn btn-pink ti-close" ></button></td>'
                document.getElementById('params_body').appendChild(son)
            } else {
                swal({
                    title: 'KEY未填写完整',
                    timer: 1000,
                    showConfirmButton: false,
                });
            }
        }

        function headers_add() {
            {#判断key是否有值#}
            if ($('.table').find('textarea[name="headers_key"]')[$('.table').find('textarea[name="headers_key"]').length - 1].value) {
                var son = document.createElement('tr')
                son.innerHTML = '<td id="api_define_module"><textarea type="text" name="headers_key"  ' +
                    'placeholder="KEY"id="td_textarea"></textarea> </td><td id="api_define_name">' +
                    '<textarea type="text" name="headers_value"placeholder="VALUE"  id="td_textarea"></textarea>' +
                    '</td><td><button onclick="headers_del(this)" class="btn btn-pink ti-close" ></button></td>'
                document.getElementById('headers_body').appendChild(son)
            } else {
                swal({
                    title: 'KEY未填写完整',
                    timer: 1000,
                    showConfirmButton: false,
                });
            }
        }

        function body_add() {
            {#判断key是否有值#}
            if ($('.table').find('textarea[name="body_key"]')[$('.table').find('textarea[name="body_key"]').length - 1].value) {
                var son = document.createElement('tr')
                son.innerHTML = '<td id="api_define_module"><textarea type="text" name="body_key"  ' +
                    'placeholder="KEY"id="td_textarea"></textarea> </td><td id="api_define_name">' +
                    '<textarea type="text" name="body_value"placeholder="VALUE"  id="td_textarea"></textarea>' +
                    '</td><td><button onclick="body_del(this)" class="btn btn-pink ti-close" ></button></td>'
                document.getElementById('body_body').appendChild(son)
            } else {
                swal({
                    title: 'KEY未填写完整',
                    timer: 1000,
                    showConfirmButton: false,
                });
            }
        }


    </script>
    <script>
        document.querySelector(".api_define_add").onclick = function () {
            var is_assert = $('.checkbox').bootstrapSwitch('state');
            var api_name = $('#api_name').val()
            var api_module = $('#api_module').val()
            var api_user = $('#api_user').val()
            var api_status = $('#api_status').val()
            var api_method = $('#api_method').val()
            var api_url = $('#api_url').val()
            var body_choice = $("input[name='body_option']:checked").val()
            var assert_choice = $("input[name='assert_option']:checked").val()
            var api_assert = $('#api_assert').val()
            var api_describe = $('#api_describe').val()
            if (body_choice == 0 || body_choice == 1) {
                var api_body = {}
                for (var i = 0; i < $('.table').find('textarea[name="body_key"]').length; i++) {
                    if ($('.table').find('textarea[name="body_key"]')[i].value) {
                        api_body[$('.table').find('textarea[name="body_key"]')[i].value] = $('.table').find('textarea[name="body_value"]')[i].value
                    }
                }
            }
            if (body_choice == 2 || body_choice == 3) {
                var api_body = JSON.parse($('#api_body').val())
            }
            if (body_choice == 5) {
                var api_body = {}
            }
            if (is_assert) {
                is_assert = 1 //标识true
            } else {
                is_assert = 0
            }
            var api_params = {}
            for (var i = 0; i < $('.table').find('textarea[name="params_key"]').length; i++) {
                if ($('.table').find('textarea[name="params_key"]')[i].value) {
                    api_params[$('.table').find('textarea[name="params_key"]')[i].value] = $('.table').find('textarea[name="params_value"]')[i].value
                }
            }
            var api_headers = {}
            for (var i = 0; i < $('.table').find('textarea[name="headers_key"]').length; i++) {
                if ($('.table').find('textarea[name="params_key"]')[i].value) {
                    api_headers[$('.table').find('textarea[name="headers_key"]')[i].value] = $('.table').find('textarea[name="headers_value"]')[i].value
                }
            }
            if (api_name, api_url) {
                $.ajax({
                    url: "{% url 'apitests:api_define_add' %}",
                    type: "POST",
                    data: {
                        "api_name": api_name,
                        "api_module": api_module,
                        "api_user": api_user,
                        "api_status": api_status,
                        "api_method": api_method,
                        "api_url": api_url,
                        "api_params": JSON.stringify(api_params),
                        "api_headers": JSON.stringify(api_headers),
                        "body_choice": body_choice,
                        "api_body": JSON.stringify(api_body),
                        "assert_choice": assert_choice,
                        "is_assert": is_assert,
                        "api_assert": api_assert,
                        "api_describe": api_describe,
                    },
                    beforeSend: function (xhr, settings) {
                        xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                    },
                    success: function (data) {
                        if (data.status) {
                            swal({
                                title: '添加成功',
                                timer: 1000,
                                showConfirmButton: false,
                            });
                            var timer = setTimeout(() => {
                                window.location.href = "{% url 'apitests:api_define_list' %}";
                                clearTimeout(timer)
                            }, 1000)
                        } else {
                            swal({
                                title: data.error_msg,
                                timer: 1000,
                                showConfirmButton: false,
                            });
                        }
                    },
                })

            } else {
                swal("数据请填写完整")

            }
        }
    </script>
{% endblock %}